package question.solution783;

import question.SolutionTemplate;

import java.util.ArrayList;
import java.util.List;

public class Solution783 implements SolutionTemplate {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int minDistance = Integer.MAX_VALUE;

    public int minDiffInBST(TreeNode root) {
        if(null == root){
            return -1;
        }
        List<Integer> numberList = new ArrayList<>();
        getArray(root, numberList);
        int minDistance = Integer.MAX_VALUE;
        for(int i=1;i<numberList.size();i++){
            int distance = numberList.get(i) - numberList.get(i-1);
            if(distance<minDistance){
                minDistance = distance;
            }
        }
        return minDistance;
    }

    private void getArray(TreeNode node, List<Integer> numberList){
        if(null != node.left){
            getArray(node.left, numberList);
        }
        numberList.add(node.val);
        if(null != node.right){
            getArray(node.right, numberList);
        }
    }


    public void test() {
        TreeNode node4 = new TreeNode(4);
        TreeNode node2 = new TreeNode(2);
        TreeNode node6 = new TreeNode(6);
        TreeNode node1 = new TreeNode(1);
        TreeNode node3 = new TreeNode(3);
        node4.left = node2;
        node4.right = node6;
        node2.left = node1;
        node2.right = node3;
        int result = minDiffInBST(node4);
        return;
    }
}
